//登录注册模块
import { reqGetCode, reqUserInfo, reqUserLogin, reqUserRegister ,reqUserLogout} from '@/api';
import { setToken,getToken,removeToken } from '@/utils/token'
//search的小仓库
//state:仓库存储数据的地方
const state = {
    code:'',
    token: getToken(),
    userInfo:{},
};
//mutations: 修改state的唯一手段
const mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    USERLOGIN(state,token){
        state.token = token;
    },
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo;
    },
    //清除本地数据
    CLEAR(state){
        //吧仓库中相关用户信息清空
        state.token ='',
        state.userInfo = {},
        //清除本地存储信息清空
        removeToken();
        
    }

};
//action:处理action,可以书写自己的业务逻辑，也可以处理异步
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone);
        if (result.code == 200) {
            commit('GETCODE', result.data);
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //注册用户
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user);
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('file'))
        }
    },
    //登陆业务【token】
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data);
        //服务器下发的token，用户唯一标识符（uuid）
        //经常通过带token找服务器要用户信息进行展示
        if (result.code == 200) {
            commit('USERLOGIN', result.data.token);
            //持久化存储token
            setToken(result.data.token)
            return 'ok';
        } else {
            return Promise.reject(new Error('file'));
        }
    },
    //获取用户信息
    async getUserInfo({commit}){
       let result = await reqUserInfo();
       if(result.code==200){
        commit('GETUSERINFO',result.data);
       }
    },
    //退出登录
    async userLogout({commit}){
        //像服务器发送请求，求出数据token
        let result = await reqUserLogout();
        //action里面不能操作state，提交mutation修改state
        if(result.code ==200){
            commit('CLEAR');
        }
    }
};
//getters: 理解为计算属性,用于简化仓库数据，让组件获取仓库的数据更加方便
//项目当中getters作用是简化仓库数据
const getters = {


};


//对外暴露一个实例
export default {
    state,
    mutations,
    actions,
    getters
}